package com.zbkj.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.constants.InvoiceConstants;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.order.StoreOrder;
import com.zbkj.common.model.order.StoreOrderInfo;
import com.zbkj.common.model.system.SystemInvoice;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.InvoiceRequest;
import com.zbkj.common.request.InvoiceSearchRequest;
import com.zbkj.common.request.InvoiceUpdateRequest;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.response.InvoiceProductResponse;
import com.zbkj.common.response.InvoiceResponse;
import com.zbkj.service.dao.SystemInvoiceDao;
import com.zbkj.service.service.StoreOrderInfoService;
import com.zbkj.service.service.StoreOrderService;
import com.zbkj.service.service.SystemInvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class SystemInvoiceServiceImpl extends ServiceImpl<SystemInvoiceDao, SystemInvoice>
        implements SystemInvoiceService {

    @Autowired
    private StoreOrderService storeOrderService;

    @Autowired
    private StoreOrderInfoService storeOrderInfoService;

    @Resource
    private SystemInvoiceDao dao;

    //添加电子发票数据库实体
    @Override
    public Boolean create(SystemInvoice systemInvoice) {
        return dao.insert(systemInvoice) > 0;
    }

    /**
     * 开具电子发票，添加
     *
     * @param   invoiceRequest|必填
     * @param realName 开票人
     */
    @Override
    public InvoiceResponse getInvoiceByOrderId(InvoiceRequest invoiceRequest, String realName) {
        String orderId = invoiceRequest.getOrderId();
        // 查询订单
        StoreOrder storeOrder = storeOrderService.getByOderId(orderId);
        if (ObjectUtil.isNull(storeOrder) || storeOrder.getIsDel() || storeOrder.getIsSystemDel()) {
            throw new CrmebException("订单不存在");
        }
        if(storeOrder.getStatus() != 2 && storeOrder.getStatus() != 3 && storeOrder.getRefundStatus() != 0){
            throw new CrmebException("订单还未完成或者订单已申请退款");
        }
        InvoiceResponse invoiceResponse = new InvoiceResponse();
        invoiceResponse.setInvoiceIssuer(realName)//开票人
                .setInvoiceName(InvoiceConstants.INVOICE_NAME)//发票名称
                .setInvoiceNumber(storeOrder.getOrderId())//20位发票号码，好像不是订单号
//                .setInvoiceDate(DateUtil.format(DateUtil.date(), Constants.INVOICE_DATE))//开票日期格式yyyy年MM月dd日
                .setInvoiceDate(DateUtil.date())
                .setBusinessName(InvoiceConstants.BUSINESS_NAME)//销售方名称
                .setBusinessTaxpayerNumber(InvoiceConstants.BUSINESS_TAXPAYER_NUMBER)//销售方税号
                .setCustomerName(storeOrder.getRealName())//购买方名称
                .setCustomerTaxpayerNumber(invoiceRequest.getCustomerTaxpayerNumber())//购买方税号字段
                .setOrderId(orderId);

        //发票商品对象列表
        List<InvoiceProductResponse> invoiceProductList = new ArrayList<>();
        List<StoreOrderInfo> infoList = storeOrderInfoService.getListByOrderNo(orderId);
        BigDecimal totalPrice = new BigDecimal("0");//金额合计
        BigDecimal totalTax = new BigDecimal("0");//税额合计
        for (StoreOrderInfo e : infoList) {
            InvoiceProductResponse invoiceProductResponse = new InvoiceProductResponse();
            BigDecimal priceAmount = new BigDecimal(e.getPayNum()).multiply(e.getPrice());//商品金额
            BigDecimal taxRate = invoiceRequest.getTaxRate();//税率填写,常量或者request请求里填写
//            BigDecimal taxRate = Constants.TAX_RATE;
            BigDecimal taxAmount = priceAmount.multiply(taxRate).divide(new BigDecimal("100"));//税额

            invoiceProductResponse.setProductId(e.getProductId())
                    .setProductName(e.getProductName())
                    .setSku(e.getSku())//规格型号字符，不大确定是这个字段
                    .setUnit("件")//单位填写
                    .setProductNum(e.getPayNum())
                    .setPrice(e.getPrice())
                    .setPriceAmount(priceAmount)
                    .setTaxRate(taxRate)
                    .setTaxAmount(taxAmount);
            invoiceProductList.add(invoiceProductResponse);
            totalPrice = totalPrice.add(priceAmount);
            totalTax = totalTax.add(taxAmount);
        }
        BigDecimal totalAmount = totalPrice.add(totalTax);//价税合计
        invoiceResponse.setInvoiceProductList(invoiceProductList)
                .setTotalPrice(totalPrice)
                .setTotalTax(totalTax)
                .setTotalAmount(totalAmount)
                .setRemarks(storeOrder.getMark());

        //数据库也创建一下支票实体，字段含有订单号，根据订单号可查询销售商品列表
        SystemInvoice invoice = new SystemInvoice();
        BeanUtil.copyProperties(invoiceResponse, invoice);
        invoice.setInvoiceDate(DateUtil.date());
        create(invoice);
        return invoiceResponse;
    }


    //根据发票id获取发票详情，商品列表字段还是需要重新去get和set
    @Override
    public InvoiceResponse invoiceInfoById(Integer id) {
        SystemInvoice invoice = getById(id);
        if (ObjectUtil.isNull(invoice)) {
            throw new CrmebException("发票未开具");
        }
        if (invoice.getIsDel().equals(true)) {
            throw new CrmebException("发票已删除");
        }
        InvoiceResponse invoiceResponse = new InvoiceResponse();
        BeanUtil.copyProperties(invoice, invoiceResponse);
        String orderId = invoice.getOrderId();

        //发票商品对象列表
        List<InvoiceProductResponse> invoiceProductList = new ArrayList<>();
        List<StoreOrderInfo> infoList = storeOrderInfoService.getListByOrderNo(orderId);
        for (StoreOrderInfo e : infoList) {
            InvoiceProductResponse invoiceProductResponse = new InvoiceProductResponse();
            BigDecimal priceAmount = new BigDecimal(e.getPayNum()).multiply(e.getPrice());//商品金额
//            BigDecimal taxRate = invoiceRequest.getTaxRate();//税率填写,常量或者request请求里填写
            BigDecimal taxRate = InvoiceConstants.TAX_RATE;
            BigDecimal taxAmount = priceAmount.multiply(taxRate).divide(new BigDecimal("100"));//税额

            invoiceProductResponse.setProductId(e.getProductId())
                    .setProductName(e.getProductName())
                    .setSku(e.getSku())//规格型号字符，不大确定是这个字段
                    .setUnit("件")//单位填写
                    .setProductNum(e.getPayNum())
                    .setPrice(e.getPrice())
                    .setPriceAmount(priceAmount)
                    .setTaxRate(taxRate)
                    .setTaxAmount(taxAmount);
            invoiceProductList.add(invoiceProductResponse);
        }
        return invoiceResponse;
    }

    /**
     * 修改电子发票
     *
     * @param id 发票id，必填
     * @param request|必填
     */
    @Override
    public Boolean updateInvoice(Integer id, InvoiceUpdateRequest request) {
        SystemInvoice invoice = getById(id);
        if (ObjectUtil.isNull(invoice)) {
            throw new CrmebException("发票未开具");
        }
        if (invoice.getIsDel().equals(true)) {
            throw new CrmebException("发票已删除");
        }
        BeanUtil.copyProperties(request, invoice);
        return updateById(invoice);
    }

    /**
     * 删除电子发票
     *
     * @param id 发票id
     */
    @Override
    public Boolean deleteById(Integer id) {
        SystemInvoice invoice = getById(id);
        if (ObjectUtil.isNull(invoice)) {
            throw new CrmebException("发票未开具");
        }
        if (invoice.getIsDel().equals(true)) {
            throw new CrmebException("发票已删除");
        }
        invoice.setIsDel(true);
        return updateById(invoice);
    }

    //分页显示发表列表
    @Override
    public CommonPage<SystemInvoice> getInvoiceList(InvoiceSearchRequest request, PageParamRequest pageParamRequest) {
        Page<SystemInvoice> startPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<SystemInvoice> lqw = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(request.getOrderNo())){
            lqw.like(SystemInvoice::getOrderId, request.getOrderNo());
        }
        if(StringUtils.isNotBlank(request.getKeywords())){
            lqw.and(i -> i.or().like(SystemInvoice::getInvoiceNumber, request.getKeywords())
                    .or().like(SystemInvoice::getCustomerName, request.getKeywords())
                    .or().like(SystemInvoice::getCustomerTaxpayerNumber, request.getKeywords())
                    .or().like(SystemInvoice::getInvoiceIssuer,request.getKeywords())
                    .or().like(SystemInvoice::getRemarks, request.getKeywords())
            );
        }
        lqw.eq(SystemInvoice::getIsDel, false);
        lqw.orderByDesc(SystemInvoice::getId).orderByDesc(SystemInvoice::getInvoiceDate);
        List<SystemInvoice> invoiceList = dao.selectList(lqw);
        return CommonPage.restPage(CommonPage.copyPageInfo(startPage, invoiceList));
    }

}